﻿using BaseUi.Tool;
using BaseUi.ViewModels;
using Common.Device.Tool;
using HandyControl.Controls;
using MaterialDesignColors.Recommended;
using Ping9719.WpfEx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BaseUi
{
    /// <summary>
    /// PprintingView.xaml 的交互逻辑
    /// </summary>
    public partial class PprintingView : UserControlBase
    {
        private bool rePrint = false;
        private static Db.MesDb Mesdb = new Db.MesDb();
        public static PprintingViewModel viewModel = new PprintingViewModel();
        private List<PprintingViewModel.item> ListItems = new List<PprintingViewModel.item>();
        private BarTender.Application btapp;
        private int pass;
        private int wait;
        private int todayPass;
        private int todayPassAll;
        private string loadmoCode;
        public PprintingView()
        {
            InitializeComponent();
            this.DataContext = viewModel;
            btapp = new BarTender.Application();
        }
        private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TextBoxCode.Focus();
            TextBoxCode.Clear();
            TextBoxCode.SelectAll();
            TextBoxCode.Background = this.Background;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //infoadd("当前工单已完成");
            InitPieView(TextBoxMoCode.Text);
        }
        private void InitPieView(string moCode)
        {
            if (CheckMocde(moCode))
            {
                loadmoCode = moCode;
                //初始化饼图
                InitPieView();
            }
            else
            {
                loadmoCode = "";
                TextBoxMoCode.Clear();
                pass = 0;
                wait = 0;
                viewModel.UpdataDataNew(pass, wait);
                viewModel.TodayPass = 0;
                viewModel.TodayPassAll = 0;
            }
        }
        private void InitPieView()
        {
            todayPass = GetTodayLinkCount(loadmoCode);
            viewModel.TodayPass = todayPass;
            pass = GetLinkCount(loadmoCode);
            wait = GetAllCount(loadmoCode) - pass;
            viewModel.UpdataDataNew(pass, wait);
            todayPassAll = GetLinkAllCount(loadmoCode);
            viewModel.TodayPassAll = todayPassAll;
        }
        internal static int GetTodayLinkCount(string moCode)
        {
            try
            {
                return Mesdb.db.Queryable<ZhiKongInfo>().Where(it => it.Code == moCode && it.PackageWorker != null && it.PackageTime > DateTime.Today).Count();
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return -1;
            }
        }
        internal static int GetLinkCount(string moCode)
        {
            try
            {
                return Mesdb.db.Queryable<ZhiKongInfo>().Where(it => it.Code == moCode && it.PackageWorker != null).Count();
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return -1;
            }
        }
        internal static int GetLinkAllCount(string moCode)
        {
            try
            {
                return Mesdb.db.Queryable<ZhiKongInfo>().Where(it => it.Code == moCode && it.PackageWorker != null).Count();
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return -1;
            }
        }
        internal static int GetAllCount(string moCode)
        {
            try
            {
                return Mesdb.db.Queryable<ZhiKongInfo>().Where(it => it.Code == moCode).Count();
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return -1;
            }
        }
        internal static bool CheckMocde(string mocode)
        {
            try
            {
                int count = Mesdb.db.Queryable<ZhiKongInfo>().
                    Where(it => it.Code == mocode).Count();
                if (count == 0)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return false;
            }
        }
        public void Boxinfoadd(string info)
        {
            textBoxInfo.AppendText(DateTime.Now.ToString() + info + "\r\n");
            Logs.Write(info, LogsType.Btapp, DateTime.Now);
        }

        private void textchange(object sender, TextChangedEventArgs e)
        {
            var nam = (sender as System.Windows.Controls.TextBox);
            nam.ScrollToEnd();
        }
        private void clear1(object sender, RoutedEventArgs e)
        {
            textBoxInfo.Clear();
        }
        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                try
                {
                    if (!TextBoxCode.Text.Contains(";"))
                    {
                        Boxinfoadd($"标签异常：{TextBoxCode.Text}");
                        return;
                    }
                    if (TextBoxMoCode.Text == "")
                    {

                        Boxinfoadd("工单号为空");
                        return;
                    }
                    if (loadmoCode != TextBoxMoCode.Text)
                    {

                        Boxinfoadd("工单号未点击确认");
                        return;
                    }
                    textBoxInfo.Clear();
                    string ones = TextBoxCode.Text.Trim();
                    var getonew = ones.Split(';');
                    string code = getonew[0];
                    if (wait == 0 && !rePrint)
                    {
                        Growl.Info("当前工单已完成！");
                        return;
                    }
                    Boxinfoadd($"输入产品编码{code}");
                    string retul = chilk(code, loadmoCode, rePrint);
                    if (retul != "OK")
                    {
                        Boxinfoadd(retul);
                        return;
                    }
                    var bat = getone(code, loadmoCode);
                    if (!rePrint) {
                        string result = UpPrintdate(code, loadmoCode, rePrint);
                        if (result != "OK")
                        {
                            Boxinfoadd(result);
                            return;
                        }
                    }
                    ApplicationTool.ProRePrint(btapp, bat);
                    Boxinfoadd($"标签打印完成");
                    InitPieView(TextBoxMoCode.Text);
                }
                catch (Exception ee)
                {
                    Boxinfoadd(ee.Message);
                }
                finally
                {
                    TextBoxCode.Clear();
                }
            }
        }

        private ZhiKongInfo getone(string sn, string mocode)
        {
            try
            {
                ZhiKongInfo lisgt1 = Mesdb.db.Queryable<ZhiKongInfo>().Where(it => it.SN== sn).First();
                return lisgt1;
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return null;
            }
        }

        internal static string UpPrintdate(string SN, string mocode, bool guozan)
        {
            Mesdb.db.BeginTran();
            try
            {
                var omt = Mesdb.db.Queryable<ZhiKongInfo>().Where(it => it.SN == SN).ToList();
                omt[0].PackageWorker = "andmin";
                omt[0].PackageTime = Mesdb.db.GetDate();


                int count = Mesdb.db.Updateable(omt).ExecuteCommand();
                if (count != 1)
                {
                    Mesdb.db.RollbackTran();
                    return "错误:更新标签数据库失败";
                }
                Mesdb.db.CommitTran();
                return "OK";
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return ee.ToString();
            }
        }

        internal static string chilk(string SN, string mocode,bool guozan)
        {
            try
            {
                var omt = Mesdb.db.Queryable<ZhiKongInfo>().Where(it => it.SN == SN).ToList();
                if (omt==null)
                {
                    return "数据库链接错误";
                }
                if (omt.Count==0)
                {
                    return "未查询到该编码";
                }
                if (omt.Count!=1)
                {
                    return "该编码的数量不为一";
                }
                if (omt[0].PackageWorker!=null&&!guozan)
                {
                    return "该编码已经过站了";
                }
                if (omt[0].Code != mocode)
                {
                    return $"工单号错误{mocode}";
                }
                if (omt[0].State != "通过")
                {
                    return $"未通过测试";
                }
                return "OK";
            }
            catch (Exception ee)
            {
                Logs.Write(ee.ToString());
                return ee.ToString();
            }
        }

        private void TextBoxCode_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void CheckBoxRePrint_Checked(object sender, RoutedEventArgs e)
        {
            var r1 = Common.View.Controls.Dialogs.TipView.Show($"确认重新打印?", new Dictionary<string, Brush> { { "确定", Common.View.Base.Colors.PrimaryColor }, { "取消", Common.View.Base.Colors.DangerColor } });

            if (r1 != "确定")
            {
                rePrint = false;
                CheckBoxRePrint.IsChecked = false;
                return;
            }
            else
            {
                Label_MouseDoubleClick(null, null);
                rePrint = true;
                return;
            }
        }

        private void CheckBoxRePrint_Unchecked(object sender, RoutedEventArgs e)
        {
            Label_MouseDoubleClick(null, null);
            rePrint = false;
        }

        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            ApplicationTool.ProCSPrint(btapp);
        }
    }
}
